@namespace Oqtane.Modules.Admin.Files
@inherits ModuleBase
@inject NavigationManager NavigationManager
@inject IFolderService FolderService
@inject IFileService FileService
@inject IStringLocalizer<Index> Localizer
@inject IStringLocalizer<SharedResources> SharedLocalizer

@if (_files != null)
{
    <div class="row">
        <div class="col-md mb-1">
            <ActionLink Action="Edit" Text="Add Folder" Class="btn btn-secondary" ResourceKey="AddFolder" />
        </div>
        <div class="col-md-8 mb-1">
            <div class="input-group">
                <span class="input-group-text">@Localizer["Folder"]:</span>
                <select class="form-select" @onchange="(e => FolderChanged(e))">
                    @foreach (Folder folder in _folders)
                    {
                        <option value="@(folder.FolderId)">@(new string('-', folder.Level * 2))@(folder.Name)</option>
                    }
                </select>
                <ActionLink Action="Edit" Text="Edit Folder" Class="btn btn-secondary" Parameters="@($"id=" + _folderId.ToString())" ResourceKey="EditFolder" />&nbsp;
            </div>
        </div>
        <div class="col-md mb-1 text-end">
            <ActionLink Action="Add" Text="Upload Files" Parameters="@($"id=" + _folderId.ToString())" ResourceKey="UploadFiles" />
        </div>
    </div>

    <Pager Items="@_files" SearchProperties="Name">
        <Header>
        <th style="width: 1px;">&nbsp;</th>
        <th style="width: 1px;">&nbsp;</th>
        <th>@SharedLocalizer["Name"]</th>
        <th>@Localizer["Modified"]</th>
        <th>@Localizer["Type"]</th>
        <th>@Localizer["Size"]</th>
        </Header>
        <Row>
            <td><ActionLink Action="Details" Text="Edit" Parameters="@($"id=" + context.FileId.ToString())" ResourceKey="Details" /></td>
            <td><ActionDialog Header="Delete File" Message="@string.Format(Localizer["Confirm.File.Delete"], context.Name)" Action="Delete" Security="SecurityAccessLevel.Admin" Class="btn btn-danger" OnClick="@(async () => await DeleteFile(context))" ResourceKey="DeleteFile" /></td>
            <td><a href="@context.Url" target="_new">@context.Name</a></td>
            <td>@context.ModifiedOn</td>
            <td>@context.Extension.ToUpper() @SharedLocalizer["File"]</td>
            <td>@string.Format("{0:0.00}", ((decimal)context.Size / 1000)) KB</td>
        </Row>
    </Pager>
    @if (_files.Count == 0)
    {
        <div class="text-center">@Localizer["NoFiles"]</div>
    }
}

@code {
    private List<Folder> _folders;
    private int _folderId = -1;
    private List<File> _files;

    public override SecurityAccessLevel SecurityAccessLevel => SecurityAccessLevel.Admin;

    protected override async Task OnParametersSetAsync()
    {
        try
        {
            _folders = await FolderService.GetFoldersAsync(PageState.Site.SiteId);

            if (_folderId == -1 && _folders.Count > 0)
            {
                _folderId = _folders[0].FolderId;
                await GetFiles();
            }
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Loading Files {Error}", ex.Message);
            AddModuleMessage(Localizer["Error.File.Load"], MessageType.Error);
        }
    }

    private async Task GetFiles()
    {
        _files = await FileService.GetFilesAsync(_folderId);
    }

    private async void FolderChanged(ChangeEventArgs e)
    {
        try
        {
            _folderId = int.Parse((string)e.Value);
            await GetFiles();
            StateHasChanged();
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Loading Files {Error}", ex.Message);
            AddModuleMessage(Localizer["Error.File.Load"], MessageType.Error);
        }
    }

    private async Task DeleteFile(File file)
    {
        try
        {
            await FileService.DeleteFileAsync(file.FileId);
            await logger.LogInformation("File Deleted {File}", file.Name);
            AddModuleMessage(string.Format(Localizer["Success.File.Delete"], file.Name), MessageType.Success);
            await GetFiles();
            StateHasChanged();
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Deleting File {File} {Error}", file.Name, ex.Message);
            AddModuleMessage(string.Format(Localizer["Error.File.Delete"], file.Name), MessageType.Error);
        }
    }
}
